<template>
  <div>
    <el-card shadow="never" class="box">
      <template #header>
        <span class="title" style="font-size: 28px; font-weight: 700">药库管理</span>
      </template>

      <!-- 1. 搜索与新增 -->
      <el-form :inline="true" class="top-bar">
        <el-form-item label="药品编号/名称：">
          <el-input v-model="search.key" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="分类：">
          <el-select v-model="search.category" placeholder="请选择" clearable style="width: 120px">
            <el-option label="西药" value="西药" />
            <el-option label="中药" value="中药" />
            <el-option label="抗生素" value="抗生素" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button type="default" style="margin-left:8px;" @click="handleClear">清空并更新</el-button>
        </el-form-item>
        
        <el-form-item class="btn-right">
          <el-button type="success" :icon="Plus" @click="handleAdd">添加新药物</el-button>
        </el-form-item>
      </el-form>

      <!-- 2. 已选择提示 -->
      <div v-if="selectedIds.length" class="batch-tip">
        <span>已选择 {{ selectedIds.length }} 项</span>
        <el-button type="danger" link @click="handleBatchDelete">清空</el-button>
      </div>

      <!-- 3. 表格（无详情按钮） -->
      <el-table :data="pageTable" stripe border size="small" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="drugCode" label="药品编号" />
        <el-table-column prop="drugName" label="药品名称" />
        <el-table-column prop="drugType" label="药品类别" />
        <el-table-column prop="drugFormat" label="规格" />
        <el-table-column prop="drugUnit" label="单位" />
        <el-table-column prop="manufacturer" label="生产厂家" />
        <el-table-column prop="drugPrice" label="单价" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 4. 分页 -->
      <el-pagination
        :current-page="page.current"
        :page-size="page.size"
        :total="filterList.length"
        layout="prev, pager, next, jumper, ->, total, slot"
        @current-change="handlePage"
        class="pagination"
      >
        <template #slot>
          跳至<el-input-number v-model="jumpPage" :min="1" :max="maxPage" controls-position="right" @change="jumpTo" style="width: 60px; margin: 0 8px;" />页
        </template>
      </el-pagination>
    </el-card>

    <!-- 5. 新增/编辑弹窗（全部字段） -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" @closed="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="药品编号" prop="drugCode">
          <el-input v-model="form.drugCode" placeholder="必填，唯一" />
        </el-form-item>
        <el-form-item label="药品名称" prop="drugName">
          <el-input v-model="form.drugName" placeholder="必填" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="form.drugType" placeholder="请选择">
            <el-option label="西药" value="西药" />
            <el-option label="中成药" value="中成药" />
            <el-option label="中药饮片" value="中药饮片" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格">
          <el-input v-model="form.drugFormat" placeholder="例：100mg" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="form.drugUnit" placeholder="例：盒" />
        </el-form-item>
        <el-form-item label="生产厂家">
          <el-input v-model="form.manufacturer" placeholder="例：华北制药" />
        </el-form-item>
        <el-form-item label="单价">
          <el-input-number v-model="form.drugPrice" :precision="2" :min="0" />
        </el-form-item>
        <el-form-item label="助记码">
          <el-input v-model="form.mnemonicCode" placeholder="例：ASPL" />
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker v-model="form.creationDate" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

/* ---------- 数据 ---------- */
const drugList = ref([])
const search = reactive({ key: '', category: '' })
const selectedIds = ref([])
const page = reactive({ current: 1, size: 10 })
const jumpPage = ref(1)

const dialogVisible = ref(false)
const dialogTitle = ref('')
const form = ref({
  drugCode: '',
  drugName: '',
  drugType: '西药',
  drugFormat: '',
  drugUnit: '',
  manufacturer: '',
  drugPrice: 0,
  mnemonicCode: '',
  creationDate: new Date().toISOString().slice(0, 10)
})
const rules = {
  drugCode: [{ required: true, message: '请输入药品编号', trigger: 'blur' }],
  drugName: [{ required: true, message: '请输入药品名称', trigger: 'blur' }]
}

/* ---------- 业务 ---------- */
const fetchDrugList = async (showSuccess = false) => {
  if (!search.key.trim() && !search.category) {
    const { data: res } = await request.get('/api/druglib/list')
    drugList.value = res || []
    if (drugList.value.length === 0) ElMessage.info('暂无药品数据')
    else if (showSuccess) ElMessage.success('查找成功')
    page.current = 1
    return
  }
  const { data: res } = await request.get('/api/druglib/list', { params: search })
  drugList.value = res || []
  if (drugList.value.length === 0) ElMessage.warning('该药品不存在')
  else if (showSuccess) ElMessage.success('查找成功')
  page.current = 1
}

const handleSearch = async () => {
  if (!search.key.trim()) {
    ElMessage.warning('请输入药品编码或名称')
    return
  }
  page.current = 1
  await fetchDrugList(true) // 传递参数标记为主动查询
}
const handleClear = async () => {
  search.key = ''
  search.category = ''
  page.current = 1
  await fetchDrugList(false) // 标记为清空刷新
  ElMessage.success('更新成功')
}

const handleAdd = () => {
  dialogTitle.value = '新增药品'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑药品'
  form.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  await ElMessageBox.confirm(`确认删除 ${row.drugName}？`, '提示', { type: 'warning' })
  await request.delete(`/api/druglib/${row.id}`)
  ElMessage.success('已删除')
  fetchDrugList()
}

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) return
  await ElMessageBox.confirm(`确认清空已选 ${selectedIds.value.length} 项？`, '提示', { type: 'warning' })
  for (const id of selectedIds.value) {
    await request.delete(`/api/druglib/${id}`)
  }
  selectedIds.value = []
  ElMessage.success('已清空')
  fetchDrugList()
}

const handlePage = (val) => { page.current = val }
const jumpTo = (val) => { page.current = val }

const resetForm = () => {
  form.value = {
    drugCode: '',
    drugName: '',
    drugType: '西药',
    drugFormat: '',
    drugUnit: '',
    manufacturer: '',
    drugPrice: 0,
    mnemonicCode: '',
    creationDate: new Date().toISOString().slice(0, 10)
  }
}

const submitForm = async () => {
  await ElMessageBox.confirm('确认保存？', '提示', { type: 'info' })
  await request({
    url: form.value.id ? `/api/druglib/${form.value.id}` : '/api/druglib',
    method: form.value.id ? 'PUT' : 'POST',
    data: form.value
  })
  ElMessage.success(form.value.id ? '修改成功' : '新增成功')
  dialogVisible.value = false
  fetchDrugList()
}

const filterList = computed(() => drugList.value)
const pageTable = computed(() => {
  const start = (page.current - 1) * page.size
  return filterList.value.slice(start, start + page.size)
})

const maxPage = computed(() => Math.ceil(filterList.value.length / page.size))

const handleSelectionChange = (val) => {
  selectedIds.value = val.map(i => i.id)
}

onMounted(() => {
  // 默认全显示，不自动搜索
  fetchDrugList()
})
</script>

<style lang="scss" scoped>
.box {
  padding: 0 20px 20px;
}
.top-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}
.no-wrap {
  flex-shrink: 0;
  white-space: nowrap;
}
.no-label {
  margin-left: 0;
  padding-left: 0;
}
.btn-right {
  margin-left: auto;
}
.batch-tip {
  margin-bottom: 12px;
  font-size: 14px;
  color: #606266;
}
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}
</style>